//
//  LoginView.m
//  CWeekly
//
//  Created by  on 12-4-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginView.h"
#import "MainViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "JSON.h"
#import "UserCenter.h"
#define HEIGHT_S 1024-55-58
#define HEIGHT_H 768-55-58

@implementation LoginView
//static LoginView* loginV=nil;
//+(LoginView*)shareLogin:(BOOL)H{
//    @synchronized(self){
//        if (loginV == nil) {
//            [[self alloc] initWithH:H]; 
//        }
//    }
//    return loginV;    
//}
-(void)dealloc{
    [dataDic release];
    [super dealloc];
}

- (id)initWithH:(BOOL)isH
{
    self = [super init];
    if (self) {
        // Initialization code
        _isH=isH;
        userField=[[UITextField alloc] initWithFrame:CGRectMake(160, 152, 250, 30)];
        userField.font=[UIFont systemFontOfSize:18];
        userField.autocapitalizationType=UITextAutocapitalizationTypeNone;
        userField.placeholder=@"点击输入邮箱";
        userField.tag=101;
        userField.textColor=[UIColor whiteColor];
        pwdField=[[UITextField alloc] initWithFrame:CGRectMake(160, 230, 250, 30)];
        pwdField.font=[UIFont systemFontOfSize:18];
        pwdField.tag=102;
        pwdField.secureTextEntry=YES;
        pwdField.textColor=[UIColor whiteColor];
        pwdField.placeholder=@"点击输入密码";
        pwdField.autocapitalizationType=UITextAutocapitalizationTypeNone;
        
        UIButton* loginBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        loginBtn.frame=CGRectMake(115, 285, 75, 40);
        [loginBtn setImage:[UIImage imageNamed:@"login_btn.png"] forState:UIControlStateNormal];
        [loginBtn addTarget:self action:@selector(logined) forControlEvents:UIControlEventTouchUpInside];
        UIButton*signupBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        signupBtn.frame=CGRectMake(350, 285, 75, 40);
        [signupBtn setImage:[UIImage imageNamed:@"signup_btn.png"] forState:UIControlStateNormal];
       [signupBtn addTarget:self action:@selector(signup) forControlEvents:UIControlEventTouchUpInside];
        
        
        UIButton* closeLogin=[UIButton buttonWithType:UIButtonTypeCustom];
        closeLogin.frame=CGRectMake(500, 20, 32, 32);
        [closeLogin addTarget:self action:@selector(closeLogin) forControlEvents:UIControlEventTouchUpInside];
        [closeLogin setImage:[UIImage imageNamed:@"closeLogin.png"] forState:UIControlStateNormal];
        
        imgv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_bg.png"]];
        imgv.frame=CGRectMake(0, 0, 550, 600);
        imgv.userInteractionEnabled=YES;
        [self addSubview:imgv];
        [imgv release];
        [imgv addSubview:userField];
        [imgv addSubview:pwdField];
        [userField release];
        [pwdField release];
        [imgv addSubview:loginBtn];
        [imgv addSubview:signupBtn];
        [imgv addSubview:closeLogin];

        userInfoView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainBG_v.png"]];
        userInfoView.frame=imgv.frame;
        userInfoView.userInteractionEnabled=YES;
        [self insertSubview:userInfoView belowSubview:imgv];
        [userInfoView release];
        table=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 400, 330) style:
               UITableViewStyleGrouped];
        table.clipsToBounds=YES;
        table.delegate=self;
        table.dataSource=self;
        table.opaque=NO;
        table.backgroundView=nil;
        table.separatorStyle=UITableViewCellSeparatorStyleNone;
        [userInfoView addSubview:table];
        table.center=CGPointMake(userInfoView.frame.size.width/2, userInfoView.frame.size.height*1/3);
        [table release];
        
        UIButton* resignBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        resignBtn.frame=CGRectMake(225, 400, 75, 40);
        [resignBtn setBackgroundImage:[UIImage imageNamed:@"resign.png"] forState:UIControlStateNormal];
        [resignBtn setTitle:@"注销" forState:UIControlStateNormal];
        [resignBtn addTarget:self action:@selector(resign) forControlEvents:UIControlEventTouchUpInside];
        [userInfoView addSubview:resignBtn];
        UIButton* closeB=[UIButton buttonWithType:UIButtonTypeCustom];
        closeB.frame=CGRectMake(500, 20, 32, 32);
        [closeB addTarget:self action:@selector(closeLogin) forControlEvents:UIControlEventTouchUpInside];
        [closeB setImage:[UIImage imageNamed:@"closeLogin.png"] forState:UIControlStateNormal];
        [userInfoView addSubview:closeB];
        load=NO;
        if (_isH) {
            self.frame = CGRectMake(0, 55, 1024, 748-58);
        }
        else {
            self.frame = CGRectMake(0, 55, 768, 1004-58);
        }
        self.backgroundColor=[UIColor clearColor];
    }
    return self;
}

-(void)closeLogin{
    [self setAlpha:0];
//    [req cancel];
    UINavigationController* controller=(UINavigationController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
   NSArray* conts= controller.viewControllers;
    MainViewController* vc;
    for (UIViewController* v in conts) {
        NSLog(@"%@",v.class.description);
        if ([[[v class]description] isEqualToString:@"MainViewController"]) {
            vc=(MainViewController*)v;
            break;
        }
    }
  UIButton* b= (UIButton*) vc.topBar.loginItem.customView;
    if (b.selected) {
        b.selected=NO;
    }
    [userField resignFirstResponder];
    [pwdField resignFirstResponder];
}
- (void)resign{
    [dataDic removeAllObjects];
    pwdField.text=@"";
    CATransition *animation = [CATransition animation];    
    animation.delegate = self;
    // 设定动画时间
    animation.duration = 0.3;
    // 设定动画快慢(开始与结束时较慢)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.type = @"rippleEffect";
    animation.subtype = kCATransitionFromRight;
    NSUInteger green = [[self subviews] indexOfObject:userInfoView];
    NSUInteger blue = [[self subviews] indexOfObject:imgv];
    [self exchangeSubviewAtIndex:blue withSubviewAtIndex:green];
    [[self layer] addAnimation:animation forKey:@"animation"];
    [[NSNotificationCenter defaultCenter] postNotificationName:RESIGN object:nil];

}
-(void)logined{
    if (userField.text.length&&pwdField.text.length) {
        
    }else {
        UIAlertView* al=[[[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入账号以及密码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [al show];

        return;
    }
    
    NSString* body=[NSString stringWithFormat:@"&param={\"userName\":\"%@\",\"password\":\"%@\"}",userField.text,pwdField.text];
    NSString* urlstr=[[SERVER stringByAppendingFormat:@"SynMgController?cmd=1004"] stringByAppendingString:body];
    NSLog(@"＋＋＋%@",urlstr);
   urlstr= [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    req=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:urlstr]];
    [req setRequestMethod:@"GET"];
    [req startSynchronous];
    NSData*resPonse=[req responseData];
    NSString*str=[[NSString alloc] initWithData:resPonse encoding:NSUTF8StringEncoding];
    str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"－－－%@",str);
    [req release];
    load=YES;
    dataDic=[[NSMutableDictionary alloc] init];
    NSDictionary* result=[str JSONValue];
    if ([[result valueForKey:@"status"] intValue]==1) {
//        登录失败
        UIAlertView* al=[[[UIAlertView alloc] initWithTitle:@"提示" message:@"登录失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [al show];
        return;
    }
    [self animate];
    id d=[[str JSONValue] valueForKey:@"json"];

    if ([d isKindOfClass:[NSDictionary class]]) {
        [dataDic addEntriesFromDictionary:d];
        [table reloadData];
        UserCenter* user=[UserCenter defaultUser];
        user.username=[dataDic valueForKey:@"userName"];
        user.userEmail=[dataDic valueForKey:@"userEmail"];
        user.userId= [dataDic valueForKey:@"userId"];
        user.isEnable=[dataDic valueForKey:@"isEnable"];
        [[NSNotificationCenter defaultCenter] postNotificationName:LOGINED object:dataDic];
    }
    else {
        return ;
    }
}

-(void)animate{
//    if (userInfoView.hidden) {
//        userInfoView.hidden=NO;
//        imgv.hidden=YES;
//    }else {
//        userInfoView.hidden=YES;
//        imgv.hidden=NO;
//    }
    CATransition *animation = [CATransition animation];    
    animation.delegate = self;
    // 设定动画时间
    animation.duration = 0.3;
    // 设定动画快慢(开始与结束时较慢)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.type = @"rippleEffect";
    animation.subtype = kCATransitionFromLeft;
    NSUInteger green = [[self subviews] indexOfObject:userInfoView];
    NSUInteger blue = [[self subviews] indexOfObject:imgv];
    [self exchangeSubviewAtIndex:green withSubviewAtIndex:blue];
    NSLog(@"%@",userInfoView.subviews);
    [[self layer] addAnimation:animation forKey:@"animation"];
    [userField resignFirstResponder];
    [pwdField resignFirstResponder];
}

-(void)signup{
    [[NSNotificationCenter defaultCenter] postNotificationName:SIGN_UP object:nil];

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (load) {
        return 3;
    }
    return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString*identify=@"cell";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:identify];
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
//        cell.backgroundColor=[UIColor clearColor];
    }
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text=[NSString stringWithFormat:@"用户ID: %@",[UserCenter defaultUser].userId];
            break;
        case 1:
            cell.textLabel.text=[NSString stringWithFormat:@"用户名: %@",[UserCenter defaultUser].username];
            break;
        case 2:
            cell.textLabel.text=[NSString stringWithFormat:@"用户邮箱: %@",[UserCenter defaultUser].userEmail];
            break;
            
        default:
            break;
    }
    cell.backgroundColor=[UIColor clearColor];
    cell.textLabel.textColor=[UIColor whiteColor];
    cell.textLabel.font=[UIFont systemFontOfSize:20];
    return  cell;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    if (self.frame.size.width>1000) {
//        [[UIImage imageNamed:@"mainBG.png"] drawInRect:rect];    
        imgv.center=CGPointMake(1024/2, (748-55-58)/2);

    }else {
//        [[UIImage imageNamed:@"mainBG_v.png"] drawInRect:rect];    
        imgv.center=CGPointMake(768/2, (1004-55-58)/2);
    }
    userInfoView.center=imgv.center;
    if([UserCenter defaultUser].username){
        userInfoView.alpha=1;
        imgv.alpha=0;
        load=YES;
        [table reloadData];
    }

}


@end
